package cn.chen.miaosha.rabbitmq;

import cn.chen.miaosha.domain.MiaoshaOrder;
import cn.chen.miaosha.domain.MiaoshaUser;
import cn.chen.miaosha.domain.OrderInfo;
import cn.chen.miaosha.redis.RedisService;
import cn.chen.miaosha.result.CodeMsg;
import cn.chen.miaosha.result.Result;
import cn.chen.miaosha.service.GoodsService;
import cn.chen.miaosha.service.MiaoshaService;
import cn.chen.miaosha.service.OrderService;
import cn.chen.miaosha.vo.GoodsVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MQReceiver {

    public static Logger logger = LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    MiaoshaService miaoshaService;

    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void miaoshaReceive(String message){
        logger.info("receive msg: "+message);
        MiaoshaMsg mm = RedisService.stringToBean(message, MiaoshaMsg.class);
        MiaoshaUser user = mm.getUser();
        Long goodsId = mm.getGoodsId();

        GoodsVO goods = goodsService.getGoodsVOById(goodsId);
        int stock = goods.getStockCount();
        //判断库存
        if(stock <= 0){
            return;
        }
        //判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goods.getId());
        if(order != null){
            return;
        }
        //减少库存 下订单 写入秒杀订单
        OrderInfo orderInfo = miaoshaService.miaosha(user, goods);

    }

//    @RabbitListener(queues = MQConfig.QUEUE)
//    public void receive(String message){
//        logger.info("receive message " + message);
//    }
//
//    @RabbitListener(queues = MQConfig.TOPIC_QUEUE1)
//    public void receiveTopic1(String message){
//        logger.info("topic queue1 message " + message);
//    }
//
//    @RabbitListener(queues = MQConfig.TOPIC_QUEUE2)
//    public void receiveTopic2(String message){
//        logger.info("topic queue2 message " + message);
//    }
//
//    @RabbitListener(queues = MQConfig.HEADERS_QUEUE)
//    public void receiveHeaders(byte[] message){
//        logger.info("header queue message " + new String(message));
//    }


}
